const mongoose = require("mongoose");
const Menu = mongoose.model("Menu");
const { rootUser } = require("../../config/env");
const { log, Resp } = require("../../config/utils");

class MenuCtrl {
	// 菜单列表
	async list(req, res, next) {
		try {
			let cond = {};
			const role = req.user.role.code;
			if(role !== rootUser.roleCode) {
				cond = { roles: role };
			}
			let menus = await Menu.find(cond);
			res.send(new Resp(1, "查询菜单成功!", menus));
		} catch (err) {
			log("red", err.stack);
			next(new Error("查询菜单出错!"));
		}
	}
	// 创建菜单
	async create(req, res, next) {
		let { name, code, icon = "", link = "", parentId = "", roles = [] } = req.body;
		if (!name) return next(new Error("缺少菜单名称!"));
		if (!code) return next(new Error("缺少菜单代码!"));
		if (!Array.isArray(roles)) roles = [roles];
		try {
			let menu = await Menu.findOne({ code });
			if (menu) return next(new Error("已存在此菜单!"));
			let result = await Menu.create({ name, code, icon, link, parentId, roles });
			res.send(new Resp(1, "创建菜单成功!", result));
		} catch (err) {
			log("red", err.stack);
			return next(new Error("创建菜单出错!"));
		}
	}

	// 修改菜单权限
	async update(req, res, next) {
		let { _id, name, code, icon = "", link = "", parentId = "", roles = []} = req.body;
		if (!_id) return next(new Error("缺少菜单ID!"));
		if(!name) return next(new Error("缺少菜单名称!"));
		if(!code) return next(new Error("缺少菜单代码!"));
		if (!Array.isArray(roles)) roles = [roles];
		try {
			let menu = await Menu.findOne({ _id });
			if (!menu) return next(new Error("未找到此菜单!"));
			menu.name = name;
			menu.code = code;
			menu.icon = icon;
			menu.link = link;
			menu.parentId = parentId;
			menu.roles = roles;
			let reuslt = await menu.save();
			res.send(new Resp(1, "修改菜单成功!", reuslt));
		} catch (err) {
			log("red", err.stack);
			return next(new Error("创建菜单出错!"));
		}
	}

	// 删除菜单权限
	async del(req, res, next) {
		let { id } = req.params;
		if (!id) return next(new Error("缺少菜单ID!"));
		try {
			let menu = await Menu.findOne({ _id: id });
			if (!menu) return next(new Error("未找到此菜单!"));
			let result = await Menu.deleteOne({ _id: id });
			if (result.ok === 1) {
				return res.send(new Resp(1, "删除菜单成功!", null));
			}
		} catch (err) {
			log("red", err.stack);
			return next(new Error("删除菜单出错!"));
		}
	}

}

module.exports = new MenuCtrl();